import requests
from bs4 import BeautifulSoup
import json
import time
import datetime


def get_domain_info(domain):
    '''
    从新网获取whois信息
    '''
    url = 'http://whois.xinnet.com/domains/{}'.format(domain)
    header = {'User-Agent': 'Mozilla/5.0'}
    result = {'Host': domain}
    domain_info_dict = {}
    try:
        r = requests.get(url, headers=header)
        r.raise_for_status()
        html = BeautifulSoup(r.text, 'lxml')
        domain_info = html.find(
            'table', {'class', 'whoisMl_tab'}).find_all('tr')
        for line in domain_info:
            line = line.text.strip().replace('\t', '').replace('\r', '').split('\n')
            if line[0].startswith('注册商'):
                result['Registrar'] = line[1].strip()
            elif line[0].startswith('注册日期'):
                CreationDate = line[1].strip()
                result['CreationDate'] = CreationDate[:CreationDate.index('T')]
            elif line[0].startswith('到期日期'):
                ExpirationDate = line[1].strip()
                result['ExpirationDate'] = ExpirationDate[:ExpirationDate.index(
                    'T')]
            elif line[0].startswith('DNS服务器'):
                result['DnsServer'] = [dns.strip()
                                       for dns in line[1:] if dns.strip()]
            else:
                pass
        StateCode = 1
        Reason = 'success'
    except Exception as e:
        e = str(e)
        StateCode = 0
        Reason = 'failed'
    domain_info_dict['StateCode'] = StateCode
    domain_info_dict['Reason'] = Reason
    domain_info_dict['Result'] = result
    return domain_info_dict


def get_domain_info2(domain):
    '''
    从站长之家获取whois信息
    '''
    url = 'http://whois.chinaz.com/{}'.format(domain)
    header = {'User-Agent': 'Mozilla/5.0'}
    result = {'Host': domain}
    domain_info_dict = {}
    try:
        r = requests.get(url, headers=header)
        r.raise_for_status()
        html = BeautifulSoup(r.text, 'lxml')
        domain_info = html.select('ul li.bor-b1s')
        for line in domain_info:
            line = line.text.strip().split('\n')
            if line[0].startswith('注册商'):
                result['Registrar'] = line[0].strip('注册商')
            elif line[0].startswith('创建时间'):
                CreationDate = line[0].strip('创建时间').replace(
                    '年', '-').replace('月', '-').replace('日', '')
                result['CreationDate'] = CreationDate
            elif line[0].startswith('过期时间'):
                ExpirationDate = line[0].strip('过期时间').replace(
                    '年', '-').replace('月', '-').replace('日', '')
                result['ExpirationDate'] = ExpirationDate
            elif line[0].startswith('DNS'):
                result['DnsServer'] = line[0].strip('DNS').split()
            else:
                pass
        StateCode = 1
        Reason = 'success'
    except Exception as e:
        e = str(e)
        StateCode = 0
        Reason = 'failed'
    domain_info_dict['StateCode'] = StateCode
    domain_info_dict['Reason'] = Reason
    domain_info_dict['Result'] = result
    return domain_info_dict


def check_domain(domain_list):
    '''
    检查域名到期时间，是否需要续费
    '''
    check_failed = []
    for domain in domain_list:
        domain_info_dict = get_domain_info2(domain)
        if not domain_info_dict['Result'].get('ExpirationDate'):
            domain_info_dict = get_domain_info(domain)
        if domain_info_dict['StateCode']:
            d1 = datetime.datetime.strptime(
                domain_info_dict['Result']['ExpirationDate'], '%Y-%m-%d')
            d2 = datetime.datetime.now()
            delta = d1 - d2
            domain_info_dict['Result']['daysleft'] = delta.days
        else:
            check_failed.append(domain)
        print(json.dumps(domain_info_dict))
        time.sleep(2)
    return check_failed


# domain_list = ['xindea.cn', 'xinidea.top', 'baidu.com', '8z.net']
domain_list = ['xinidea.cn']
check_failed = check_domain(domain_list)

i = 0
while i < 3:
    i += 1
    check_domain(check_failed)
